package com.tuniu.agents.common.controller;

import com.tuniu.agents.advisor.ChatEnvironmentMemory;
import com.tuniu.agents.common.AgentsConstants;
import com.tuniu.agents.common.entity.ClientInfo;
import com.tuniu.agents.common.i18n.I18nConstants;
import com.tuniu.agents.common.message.SuggestionQuestion;
import com.tuniu.agents.common.message.adaper.AdapterRecQuestion;
import com.tuniu.agents.common.service.TraceService;
import com.tuniu.agents.impl.base.Analyst;
import com.tuniu.agents.util.I18nUtil;
import com.tuniu.agents.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * Suggestion API, does not automatically generate session ID
 */
@Slf4j
@RestController
public class SuggestionController {

    public static final String SUCCESS_CODE = "710000";

    @Autowired
    private Analyst analyst;

    @Autowired
    private ChatEnvironmentMemory chatEnvironmentMemory;

    @Autowired
    private TraceService traceService;

    /**
     * Recommend questions based on session ID
     *
     * @param request Request parameters
     * @return ResponseEntity with suggestions
     */
    @RequestMapping(path = "/api/suggestions", method = RequestMethod.POST)
    public ResponseEntity<Response> suggestions(HttpServletRequest request, @RequestBody SuggestionRequest suggestionRequest) {
        Response response;
        if (StringUtils.isNotBlank(suggestionRequest.conversation_id)) {

            // Record Trace information
            traceService.trace(suggestionRequest.conversation_id);

            String lastAgentId = Optional.ofNullable(this.chatEnvironmentMemory.get(suggestionRequest.conversation_id, AgentsConstants.AgentsConversationEnvironmentKey.LAST_SELECTION_AGENT_ID)).map(Object::toString).orElse(null); // Last used AgentId
            if (StringUtils.isNotBlank(lastAgentId)) {
                // If it is SelectionAgents, directly recommend
                try {
                    List<AdapterRecQuestion> questions = analyst.callQuestion(suggestionRequest.conversation_id, suggestionRequest.message);
                    response = new Response(true, "true", SUCCESS_CODE, questions);
                    return ResponseEntity.ok(response);
                } catch (Exception e) {
                    log.error("Recommendation exception", e);
                    return ResponseEntity.ok(new Response(true, "true", SUCCESS_CODE, List.of()));
                }
            }

            // When there is historical data, default recommendation takes the departure and arrival cities recorded in global variables
            return ResponseEntity.ok(new Response(true, "true", SUCCESS_CODE, null));
        }

        // Parse parameter 'c' to get city name
        String positionCity = I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_SHANGHAI);
        String cParam = request.getParameter(AgentsConstants.FrontendParamKey.PARAM_ROOT_KEY);
        if (cParam != null) {
            ClientInfo clientInfo = JsonUtil.fromJson(cParam, ClientInfo.class);
            if (!StringUtils.isEmpty(clientInfo.getCn())) {
                positionCity = clientInfo.getCn();
            }
        }
        // Return default recommendations
        response = new Response(true, "true", SUCCESS_CODE, getSuggestionQuestions(positionCity));
        return ResponseEntity.ok(response);
    }

    /**
     * Generate default questions
     */
    private List<SuggestionQuestion> getSuggestionQuestions(String positionCity) {
        if (StringUtils.isEmpty(positionCity)) {
            positionCity = I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_SHANGHAI);
        }

        // Default suggestion one
        String suggestionOne;
        String destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_BEIJING);
        if (destinationCity.equals(positionCity)) {
            destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_NANJING);
        }
        suggestionOne = I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_BUSINESS_TRIP, new Object[]{positionCity,destinationCity});

        // Default suggestion two
        String suggestionTwo;
        destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_XIAMEN);
        if (destinationCity.equals(positionCity)) {
            destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_SANYA);
        }
        suggestionTwo = I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_FLIGHT_RECOMMENDATION, new Object[]{positionCity,destinationCity});

        String suggestionThree;
        destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_BEIJING);
        if (destinationCity.equals(positionCity)) {
            destinationCity=I18nUtil.getMessage(I18nConstants.COMMON_CITY_NAME_SHANGHAI);
        }
        suggestionThree = I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_TRAIN_SCHEDULE, new Object[]{positionCity,destinationCity});

        List<SuggestionQuestion> suggestionQuestions = List.of(
                new SuggestionQuestion(suggestionOne, ""),
                new SuggestionQuestion(suggestionTwo, ""),
                new SuggestionQuestion(suggestionThree, ""),
                new SuggestionQuestion(I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_HOTEL_RECOMMENDATION), ""),
                new SuggestionQuestion(I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_SCENIC_SPOTS), ""),
                new SuggestionQuestion(I18nUtil.getMessage(AgentsConstants.FrontendParamKey.SUGGESTION_ORDER_QUERY), "")
        );
        return suggestionQuestions;
    }

    public record Response(boolean success, String msg, String errorCode, Object data) {

    }

    public record SuggestionRequest(String conversation_id, String message, String responseId) {

    }

}
